import React, { Component } from 'react';
import { connect } from '../../sage/connect';
import { bindActionCreators } from 'redux';
import * as actions from '../../sage/actions/home';
import PreLoad from '../../util/preload'
import _ from 'lodash';
import { Icon } from 'antd';
import './style.scss'

interface IProps {
    weather: any,
    cityList: Array<any>,
    postion: any,
    [propName: string]: any,
}
@connect((state: any) => ({ ...state.home }), (dispatch: any) => (bindActionCreators(actions, dispatch)))
class HomePage extends Component<IProps, any> {
    constructor(props: IProps) {
        super(props)
        props.cacheLifecycles.didCache(this.componentDidCache.bind(this))
        props.cacheLifecycles.didRecover(this.componentDidRecover.bind(this))
    }
    readonly state = {
        spin: false,
        bgIndex: 1,
    }
    private cityCode: string | null = this.props.match.params.cityCode || null;
    private PM = [
        { text: '优', pm: [0, 35], color: '#40c057' },
        { text: '良', pm: [35, 75], color: '#82c91e' },
        { text: '轻度污染', pm: [75, 115], color: '#f76707' },
        { text: '中度污染', pm: [115, 150], color: '#e03131' },
        { text: '重度污染', pm: [150, 250], color: '#841c3c' },
        { text: '严重污染', pm: [250, 0], color: '#841c3c' },
    ]
    timer: NodeJS.Timeout | undefined;
    private getPMText(pm: number): any {
        if (isNaN(Number(pm))) return {};
        const result = _.filter(this.PM, item => {
            if (pm >= item.pm[0]) {
                if (item[1] === 0 || pm < item.pm[1]) {
                    return true;
                } else {
                    return false
                }
            } else {
                return false
            }
        })
        return result[0]
    }
    componentDidMount() {
        if (!this.cityCode) {
            this.props.getGeographicalLocation({
                url: 'https://restapi.amap.com/v3/ip?output=json&key=c79aeb4171f72f162217f854cb1f296e',
            })
        } else {
            this.props.getWeatherInfo({
                url: 'http://api.help.bj.cn/apis/weather/',
                parameter: {
                    id: this.cityCode
                }
            })
        }
        this.timer = setInterval(() => {
            this.setBgIndex();
        }, 1000 * 8)
        this.setBgIndex();
        PreLoad.preload(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'])
    }
    private componentDidCache() {
        this.timer && clearInterval(this.timer);
    }
    private componentDidRecover() {
        this.cityCode = this.props.match.params.cityCode || this.props.postion.CityCode;
        this.props.getWeatherInfo({
            url: 'http://api.help.bj.cn/apis/weather/',
            parameter: {
                id: this.cityCode
            }
        })
        this.timer = setInterval(() => {
            this.setBgIndex();
        }, 1000 * 8)
    }
    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }
    UNSAFE_componentWillReceiveProps(nextProps: any) {
        const oldCityCode: string | null = this.props.postion.CityCode || null;
        const CityCode: string | null = nextProps.postion.CityCode || null;
        if ((!oldCityCode) && CityCode) {
            this.props.getWeatherInfo({
                url: 'http://api.help.bj.cn/apis/weather/',
                parameter: {
                    id: CityCode
                }
            })
        }
        if (this.state.spin) {
            this.setState({
                spin: false
            })
        }
    }
    private refresh() {
        const CityCode = this.cityCode || this.props.postion.CityCode;
        if (CityCode) {
            this.props.getWeatherInfo({
                url: 'http://api.help.bj.cn/apis/weather/',
                parameter: {
                    id: CityCode
                }
            })
            this.setState({
                spin: true
            })
        }
    }
    private goCityList() {
        this.props.history.push('/cityList')
    }
    private setBgIndex() {
        let index = Math.ceil(Math.random() * 11);
        while (index === this.state.bgIndex) {
            index = Math.ceil(Math.random() * 11);
        }
        this.setState({
            bgIndex: index
        })
    }
    render() {
        const { city = "", weather = '', weatherimg = '', temp = '', pm25 = null, wd = '', wdenimg = '', today = '', uptime = '' } = this.props.weather;
        return (
            <div className="home-page" style={{ backgroundImage: `url(../images/homebg_${this.state.bgIndex}.jpg)` }}>
                <header className="flex align-center ">
                    <Icon type="reload" spin={this.state.spin} onClick={this.refresh.bind(this)} />
                    <p className="tody">{today}</p>
                    <Icon type="menu" onClick={this.goCityList.bind(this)} />
                </header>
                <div className="flex-column align-center container">
                    <p className="city">{city}</p>
                    <img src={weatherimg} alt="" />
                    <div className="flex align-center">
                        <p className="temp">{temp}</p>
                        <div>
                            <p>°C</p>
                            <p>{weather}</p>
                        </div>
                    </div>
                    <div className="flex align-center wden">
                        <img src={wdenimg} alt="" />
                        <p>{wd}</p>
                    </div>
                    <p className="pm" style={{ backgroundColor: this.getPMText(pm25).color }}>
                        <span>{pm25}</span>
                        {this.getPMText(pm25).text}
                    </p>
                    <p className="uptime">更新时间：{uptime}</p>
                </div>
            </div>
        )
    }
}
export default HomePage
